﻿namespace com.vs.General
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.IO;
    using System.Text;
    using System.Xml;
    using System.Xml.Schema;
    using System.Xml.Serialization;
    using System.Xml.XPath;
    using System.Xml.Xsl;

    public class XMLDocManager
    {
        private const string _DATE = "DATE";
        public const string _ROOT = "ROOT";
        public const string _ROW = "ROW";
        private const string _TIME = "TIME";
        public const string _USER_SETTING_CONFIG = "UserSettings.config";
        private StringBuilder _valErrorMsgs;
        public const string _XML = "XML";
        public const string _XML_HEADER = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
        private const string _XSL_NAMESPACE = "http://www.w3.org/1999/XSL/Transform";
        private const string _XSL_PREFIX = "xsl";

        public static string AddRoot(string root, string xml)
        {
            XmlTextWriter writer = null;
            string str;
            try
            {
                StringBuilder sb = new StringBuilder();
                writer = new XmlTextWriter(new StringWriter(sb));
                writer.WriteStartElement(root);
                writer.WriteRaw(xml);
                writer.WriteEndElement();
                writer.Flush();
                str = sb.ToString();
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                }
            }
            return str;
        }

        public static List<KeyValuePair<string, KeyValuePair<string, object>>> BuildQueryCondition(string stXML)
        {
            List<KeyValuePair<string, KeyValuePair<string, object>>> list = null;
            string key = null;
            XmlDocument document = new XmlDocument();
            document.LoadXml(stXML);
            if (document != null)
            {
                XmlNodeList elementsByTagName = document.GetElementsByTagName("Conditions");
                if ((elementsByTagName != null) && (elementsByTagName.Count > 0))
                {
                    list = new List<KeyValuePair<string, KeyValuePair<string, object>>>();
                    foreach (XmlNode node in elementsByTagName[0].ChildNodes)
                    {
                        KeyValuePair<string, object> pair;
                        if (StringManager.IsEmpty(node.InnerText) || StringManager.Equals(node.InnerText, "null"))
                        {
                            goto Label_0234;
                        }
                        if ((node.Attributes != null) && (node.Attributes.Count > 0))
                        {
                            switch (node.Attributes[0].Value.ToLower())
                            {
                                case "ge":
                                    key = ">=";
                                    goto Label_0200;

                                case "le":
                                    key = "<=";
                                    goto Label_0200;

                                case "gt":
                                    key = ">";
                                    goto Label_0200;

                                case "lt":
                                    key = "<";
                                    goto Label_0200;

                                case "ne":
                                    key = "<>";
                                    goto Label_0200;

                                case "like":
                                    key = " LIKE ";
                                    goto Label_0200;

                                case "is not null":
                                    key = " IS NOT NULL ";
                                    goto Label_0200;

                                case "is null":
                                    key = " IS NULL ";
                                    goto Label_0200;
                            }
                            key = " = ";
                        }
                        else
                        {
                            key = "=";
                        }
                    Label_0200:
                        pair = new KeyValuePair<string, object>(key, node.InnerText);
                        KeyValuePair<string, KeyValuePair<string, object>> item = new KeyValuePair<string, KeyValuePair<string, object>>(node.Name.Replace("_DOT_", "."), pair);
                        list.Add(item);
                    Label_0234:;
                    }
                    return list;
                }
            }
            return null;
        }

        public static XsltArgumentList CreateXsltArgList(string[] keyVals)
        {
            XsltArgumentList list = new XsltArgumentList();
            if (keyVals != null)
            {
                foreach (string str in keyVals)
                {
                    if ((str != null) && !(str == ""))
                    {
                        string name = str.Substring(0, str.IndexOf("=")).ToUpper().Trim();
                        string parameter = str.Substring(str.IndexOf("=") + 1).Trim();
                        list.AddParam(name, "", parameter);
                    }
                }
            }
            return list;
        }

        public static object Deserialize(string type, string xml)
        {
            return Deserialize(ReflectionManager.GetType(type), xml);
        }

        public static object Deserialize(Type type, string xml)
        {
            XmlTextReader reader = null;
            object obj2;
            try
            {
                reader = new XmlTextReader(xml, XmlNodeType.Element, null) {
                    WhitespaceHandling = WhitespaceHandling.None
                };
                obj2 = Deserialize(type, reader);
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
            }
            return obj2;
        }

        public static object Deserialize(Type type, XmlNode node)
        {
            XmlNodeReader reader = null;
            object obj2;
            try
            {
                reader = new XmlNodeReader(node);
                obj2 = Deserialize(type, reader);
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
            }
            return obj2;
        }

        public static object Deserialize(Type type, XmlReader reader)
        {
            XmlSerializer serializer = new XmlSerializer(type);
            return serializer.Deserialize(reader);
        }

        public static object Deserialize(string dllName, string fullName, string xml)
        {
            return Deserialize(ReflectionManager.GetType(dllName, fullName), xml);
        }

        public static object Deserialize(Type type, string xmlData, string nameSpace)
        {
            XmlTextReader xmlReader = null;
            object obj2;
            try
            {
                XmlSerializer serializer = new XmlSerializer(type, nameSpace);
                xmlReader = new XmlTextReader(xmlData, XmlNodeType.Element, null) {
                    WhitespaceHandling = WhitespaceHandling.None
                };
                obj2 = serializer.Deserialize(xmlReader);
            }
            finally
            {
                if (xmlReader != null)
                {
                    xmlReader.Close();
                }
            }
            return obj2;
        }

        public static string ReadNodeValue(string xml, string nodeName)
        {
            XmlDocument document = new XmlDocument();
            document.LoadXml(xml);
            if (document != null)
            {
                XmlNodeList elementsByTagName = document.GetElementsByTagName(nodeName);
                if ((elementsByTagName != null) && (elementsByTagName.Count > 0))
                {
                    XmlNode node = elementsByTagName[0];
                    return node.InnerText;
                }
            }
            return "";
        }

        public static XmlDocument ReadUserConfig(string user)
        {
            Stream inStream = null;
            XmlTextReader reader = null;
            XmlTextWriter writer = null;
            XmlDocument document2;
            try
            {
                inStream = FileManager.GetIsolatedStream(user);
                inStream.Flush();
                XmlDocument document = new XmlDocument();
                if ((inStream != null) && (inStream.Length > 0))
                {
                    document.Load(inStream);
                }
                else
                {
                    StringBuilder sb = new StringBuilder();
                    writer = new XmlTextWriter(new StringWriter(sb));
                    writer.WriteStartDocument();
                    writer.WriteStartElement("configuration");
                    writer.WriteStartElement("DisplaySettings");
                    writer.WriteEndElement();
                    writer.WriteStartElement("UserScreenSettings");
                    writer.WriteEndElement();
                    writer.WriteEndElement();
                    writer.Flush();
                    reader = new XmlTextReader(new StringReader(sb.ToString()));
                    document.Load(reader);
                }
                document2 = document;
            }
            finally
            {
                if (inStream != null)
                {
                    inStream.Close();
                }
                if (reader != null)
                {
                    reader.Close();
                }
                if (writer != null)
                {
                    writer.Close();
                }
            }
            return document2;
        }

        public static ArrayList ReadXsltMappings(string path, string fileName)
        {
            XmlDocument document = new XmlDocument();
            document.Load(Path.Combine(path, fileName));
            ArrayList list = new ArrayList();
            if (document.ChildNodes.Count > 0)
            {
                XmlNamespaceManager nsmgr = new XmlNamespaceManager(document.NameTable);
                nsmgr.AddNamespace("xsl", "http://www.w3.org/1999/XSL/Transform");
                XmlNodeList list2 = document.SelectNodes("/xsl:stylesheet/xsl:template[@match != '/']", nsmgr);
                for (int i = 0; (list2 != null) && (i < list2.Count); i++)
                {
                    string str = list2[i].Attributes["match"].Value;
                    list.Add(str.Substring(str.LastIndexOf("/") + 1));
                    list.Add(list2[i].SelectSingleNode("xsl:if/xsl:attribute", nsmgr).Attributes["name"].Value);
                }
            }
            return list;
        }

        public static string RemoveDeclaration(string xml)
        {
            if (xml != null)
            {
                while (xml.IndexOf("<?") >= 0)
                {
                    xml = xml.Substring(xml.IndexOf("?>", xml.IndexOf("<?")) + 2);
                }
            }
            return xml;
        }

        public static XmlNode RetrieveNodeForSection(FileStream stream, string section)
        {
            XmlNode node;
            try
            {
                XmlDocument document = new XmlDocument();
                if ((stream != null) && (stream.Length > 0))
                {
                    document.Load(stream);
                }
                node = document.SelectSingleNode(section);
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }
            }
            return node;
        }

        public static XmlNode RetrieveNodeForSection(string filename, string section)
        {
            FileStream stream = null;
            XmlNode node;
            try
            {
                stream = new FileStream(filename, FileMode.Open);
                node = RetrieveNodeForSection(stream, section);
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }
            }
            return node;
        }

        public static XmlNode RetrieveNodeFromAppConfig(string section)
        {
            return RetrieveNodeForSection(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile, section);
        }

        private void SchemaValidationEventHandler(object sender, ValidationEventArgs args)
        {
            this._valErrorMsgs.Append(args.Exception.Message).Append(";");
        }

        public static string Serialize(object o, Encoding enc)
        {
            XmlTextWriter writer = null;
            string str;
            try
            {
                if (enc == null)
                {
                    enc = Encoding.UTF8;
                }
                writer = new XmlTextWriter(new MemoryStream(), enc);
                new XmlSerializer(o.GetType()).Serialize((XmlWriter) writer, o);
                byte[] bytes = ((MemoryStream) writer.BaseStream).ToArray();
                writer.Flush();
                str = enc.GetString(bytes, 0, bytes.Length).Trim();
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                }
            }
            return str;
        }

        public static void SerializeToFile(object o, Encoding enc, string filepath)
        {
            XmlTextWriter writer = null;
            try
            {
                XmlDocument document = new XmlDocument();
                string xml = RemoveDeclaration(Serialize(o, null));
                document.LoadXml(xml);
                XmlSerializer serializer = new XmlSerializer(document.GetType());
                if (!StringManager.IsEmpty(filepath))
                {
                    writer = new XmlTextWriter(filepath, Encoding.UTF8);
                    serializer.Serialize((XmlWriter) writer, document);
                    writer.Flush();
                }
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                }
            }
        }

        public static void SerializeToIsolatedStorageFile(object o, Encoding enc, string fileName)
        {
            Stream isolatedStream = null;
            try
            {
                XmlDocument document = new XmlDocument();
                string xml = RemoveDeclaration(Serialize(o, null));
                document.LoadXml(xml);
                XmlSerializer serializer = new XmlSerializer(document.GetType());
                if (!StringManager.IsEmpty(fileName))
                {
                    isolatedStream = FileManager.GetIsolatedStream(fileName, FileMode.OpenOrCreate);
                    isolatedStream.SetLength(0);
                    serializer.Serialize(isolatedStream, document);
                    isolatedStream.Flush();
                }
            }
            finally
            {
                if (isolatedStream != null)
                {
                    isolatedStream.Close();
                }
            }
        }

        public static void TransformFile(string xmlFile, string xslFile, Encoding enc, params string[] keyVals)
        {
            string filename = null;
            XmlTextWriter writer = null;
            try
            {
                if (enc == null)
                {
                    enc = Encoding.UTF8;
                }
                XmlDocument document = new XmlDocument();
                document.Load(xmlFile);
                XslTransform transform = new XslTransform();
                transform.Load(xslFile, new XmlUrlResolver());
                XsltArgumentList args = null;
                if ((keyVals != null) && (keyVals.Length > 0))
                {
                    args = CreateXsltArgList(keyVals);
                }
                filename = Path.GetTempFileName();
                writer = new XmlTextWriter(filename, enc) {
                    Formatting = Formatting.Indented
                };
                transform.Transform((IXPathNavigable) document, args, (XmlWriter) writer, null);
                writer.Flush();
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                }
            }
            File.Copy(filename, xmlFile, true);
            if ((filename != null) && FileManager.Exists(filename))
            {
                FileManager.Delete(filename);
            }
        }

        public static string TransformString(string xml, string xsl, Encoding enc, params string[] keyVals)
        {
            XmlTextReader stylesheet = null;
            XmlTextWriter writer = null;
            string str;
            try
            {
                if (enc == null)
                {
                    enc = Encoding.UTF8;
                }
                XmlDocument document = new XmlDocument();
                document.LoadXml(xml);
                stylesheet = new XmlTextReader(new StringReader(xsl)) {
                    WhitespaceHandling = WhitespaceHandling.None
                };
                XslTransform transform = new XslTransform();
                transform.Load(stylesheet, new XmlUrlResolver(), new XMLDocManager().GetType().Assembly.Evidence);
                XsltArgumentList args = null;
                if ((keyVals != null) && (keyVals.Length > 0))
                {
                    args = CreateXsltArgList(keyVals);
                }
                writer = new XmlTextWriter(new MemoryStream(), enc) {
                    Formatting = Formatting.None
                };
                transform.Transform((IXPathNavigable) document, args, (XmlWriter) writer, null);
                byte[] bytes = ((MemoryStream) writer.BaseStream).ToArray();
                writer.Flush();
                str = enc.GetString(bytes, 0, bytes.Length).Trim();
            }
            finally
            {
                if (stylesheet != null)
                {
                    stylesheet.Close();
                }
                if (writer != null)
                {
                    writer.Close();
                }
            }
            return str;
        }

        public static string TransformStringWithFile(string xml, string xslFile, Encoding enc, params string[] keyVals)
        {
            XmlTextWriter writer = null;
            string str;
            try
            {
                if (enc == null)
                {
                    enc = Encoding.UTF8;
                }
                XmlDocument document = new XmlDocument();
                document.LoadXml(xml);
                XslTransform transform = new XslTransform();
                transform.Load(xslFile, new XmlUrlResolver());
                XsltArgumentList args = null;
                if ((keyVals != null) && (keyVals.Length > 0))
                {
                    args = CreateXsltArgList(keyVals);
                }
                writer = new XmlTextWriter(new MemoryStream(), enc) {
                    Formatting = Formatting.None
                };
                transform.Transform((IXPathNavigable) document, args, (XmlWriter) writer, null);
                byte[] bytes = ((MemoryStream) writer.BaseStream).ToArray();
                writer.Flush();
                str = enc.GetString(bytes, 0, bytes.Length).Trim();
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                }
            }
            return str;
        }

        public string ValidateSchema(string xml, string targetNameSpace, string schemaPath)
        {
            this._valErrorMsgs = new StringBuilder();
            try
            {
                XmlReaderSettings settings = new XmlReaderSettings();
                settings.Schemas.Add(targetNameSpace, schemaPath);
                settings.ValidationType = ValidationType.Schema;
                settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings;
                settings.ValidationEventHandler += new ValidationEventHandler(this.SchemaValidationEventHandler);
                using (StringReader reader = new StringReader(xml))
                {
                    XmlReader reader2 = XmlReader.Create(reader, settings);
                    while (reader2.Read())
                    {
                    }
                }
            }
            catch (XmlException exception)
            {
                this._valErrorMsgs.Append(exception.Message).Append(";");
            }
            return this._valErrorMsgs.ToString();
        }

        public static void WriteUserConfig(string user, XmlDocument xmlDoc)
        {
            Stream isolatedStream = null;
            try
            {
                if ((xmlDoc != null) && !StringManager.IsEmpty(user))
                {
                    XmlSerializer serializer = new XmlSerializer(xmlDoc.GetType());
                    isolatedStream = FileManager.GetIsolatedStream(user);
                    isolatedStream.SetLength(0);
                    serializer.Serialize(isolatedStream, xmlDoc);
                    isolatedStream.Flush();
                }
            }
            finally
            {
                if (isolatedStream != null)
                {
                    isolatedStream.Close();
                }
            }
        }

        public static void WriteXsltMappings(string[] fromElts, string[] toElts, string path, string elementName, string fileName)
        {
            XmlTextWriter writer = null;
            try
            {
                writer = new XmlTextWriter(Path.Combine(path, fileName), null) {
                    Formatting = Formatting.Indented
                };
                writer.WriteStartDocument();
                writer.WriteStartElement("xsl", "stylesheet", "http://www.w3.org/1999/XSL/Transform");
                writer.WriteAttributeString("version", "1.0");
                writer.WriteStartElement("xsl", "output", "http://www.w3.org/1999/XSL/Transform");
                writer.WriteAttributeString("method", "xml");
                writer.WriteAttributeString("indent", "yes");
                writer.WriteEndElement();
                writer.WriteStartElement("xsl", "template", "http://www.w3.org/1999/XSL/Transform");
                writer.WriteAttributeString("match", "/");
                writer.WriteStartElement("xsl", "element", "http://www.w3.org/1999/XSL/Transform");
                writer.WriteAttributeString("name", "ROOT");
                writer.WriteStartElement("xsl", "element", "http://www.w3.org/1999/XSL/Transform");
                writer.WriteAttributeString("name", elementName);
                for (int i = 0; i < fromElts.Length; i++)
                {
                    writer.WriteStartElement("xsl", "apply-templates", "http://www.w3.org/1999/XSL/Transform");
                    writer.WriteAttributeString("select", "ROOT/ROW/" + fromElts[i]);
                    writer.WriteEndElement();
                }
                writer.WriteEndElement();
                writer.WriteEndElement();
                writer.WriteEndElement();
                for (int j = 0; j < fromElts.Length; j++)
                {
                    writer.WriteStartElement("xsl", "template", "http://www.w3.org/1999/XSL/Transform");
                    writer.WriteAttributeString("match", "ROOT/ROW/" + fromElts[j]);
                    writer.WriteStartElement("xsl", "if ", "http://www.w3.org/1999/XSL/Transform");
                    writer.WriteAttributeString("test", "current() != ''");
                    writer.WriteStartElement("xsl", "attribute ", "http://www.w3.org/1999/XSL/Transform");
                    writer.WriteAttributeString("name", toElts[j]);
                    writer.WriteStartElement("xsl", "value-of ", "http://www.w3.org/1999/XSL/Transform");
                    if ((fromElts[j].IndexOf("DATE") != -1) || (fromElts[j].IndexOf("TIME") != -1))
                    {
                        writer.WriteAttributeString("select", "concat(concat(substring(current(),0,11),'T'),substring(current(),11,8))");
                    }
                    else
                    {
                        writer.WriteAttributeString("select", "current()");
                    }
                    writer.WriteEndElement();
                    writer.WriteEndElement();
                    writer.WriteEndElement();
                    writer.WriteEndElement();
                }
                writer.WriteEndElement();
                writer.Flush();
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                }
            }
        }
    }
}

